<template>
  <div class="app-container">
    <el-dialog
      :title="id ? '修改' : '新增'"
      :visible.sync="visible"
      width="800px"
      :before-close="handleClose"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="楼层" prop="mapId">
          <el-select
            v-model="form.mapId"
            placeholder="请选择楼层"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in floorArr"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="书架" prop="posId">
          <el-select
            v-model="form.posId"
            placeholder="请选择书架"
            clearable
            filterable
            remote
            :remote-method="remoteMethod"
            size="small"
            @clear="handleClear"
            @change="rquestposId"
          >
            <el-option
              v-for="dict in posArr"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.posId" label="架层" prop="caseId">
          <el-select
            v-model="form.caseId"
            placeholder="请选择架层"
            clearable
            filterable
            remote
            :remote-method="remoteMethod1"
            size="small"
            @clear="handleClear1"
          >
            <el-option
              v-for="dict in caseArr"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择类型"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in AssetLocationType"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资产" prop="assetId">
          <tableCom ref="tableCom" @selectAsset="selectAsset" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="sub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import editorCom from "@/components/Editor";
import { addLocation, editLocation } from "@/api/location";
import { getfloorArr } from "@/api/map";
import { getEnums } from "@/api/public";
import { positionArr } from "@/api/model";
import { getcaseArr } from "@/api/case";
import tableCom from "./assetTable";
export default {
  name: "Add",
  components: {
    editorCom,
    tableCom,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    objTarget: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      form: {},
      rules: {
        mapId: [{ required: true, message: "请选择楼层", trigger: "change" }],
        posId: [{ required: true, message: "请选择书架", trigger: "change" }],
        caseId: [{ required: true, message: "请选择架层", trigger: "change" }],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        assetId: [{ required: true, message: "请选择类型", trigger: "change" }],
      },
      floorArr: [],
      AssetLocationType: [],
      posArr: [],
      caseArr: [],
    };
  },
  watch: {
    id: {
      handler(val) {
        if (val) {
          this.giveDetail();
        }
      },
      deep: false,
      immediate: true,
    },
    visible: {
      handler(val) {
        if (val) {
          this.requestfloorArr(0);
          this.requestEnums();
          this.requestpositionArr("");
        }
      },
      deep: false,
      immediate: true,
    },
  },
  methods: {
    rquestcaseArr(name, objTarget) {
      this.caseArr = [];
      const posId = this.form.posId;
      if (!posId) {
        return;
      }
      getcaseArr(name, posId)
        .then((res) => {
          if (res.success) {
            const arr = res?.data ?? [];
            if (arr.length > 0) {
              arr.map((item) => {
                const obj = {
                  label: item?.caseName ?? "",
                  value: item?.caseId ?? "",
                };
                this.caseArr.push(obj);
              });
              if (objTarget) {
                this.$set(this.form, "caseId", objTarget.caseId);
              }
            }
          }
        })
        .catch((err) => {});
    },
    handleClear() {
      this.requestpositionArr("");
    },
    handleClear1() {
      this.rquestcaseArr("");
    },
    selectAsset(ctrlId, assetId) {
      this.$set(this.form, "ctrlId", ctrlId);
      this.$set(this.form, "assetId", assetId);
    },
    remoteMethod(query) {
      this.requestpositionArr(query);
    },
    remoteMethod1(query) {
      this.rquestcaseArr(query);
    },
    requestpositionArr(name) {
      this.posArr = [];
      positionArr("Shelf", name)
        .then((res) => {
          if (res.success) {
            const arr = res?.data ?? [];
            if (arr.length > 0) {
              arr.map((item) => {
                const obj = {
                  label: item?.posName ?? "",
                  value: item?.posId ?? "",
                };
                this.posArr.push(obj);
              });
            }
          }
        })
        .catch((err) => {});
    },
    requestEnums() {
      this.AssetLocationType = [];
      getEnums()
        .then((res) => {
          const obj = res?.data?.AssetLocationType ?? {};
          if (Object.keys(obj).length > 0) {
            for (const key in obj) {
              this.AssetLocationType.push({
                label: obj[key],
                value: key,
              });
            }
          }
        })
        .catch((err) => {});
    },
    requestfloorArr(id) {
      this.floorArr = [];
      getfloorArr(id)
        .then((res) => {
          if (res.success) {
            const arr = res?.data ?? [];
            if (arr.length > 0) {
              arr.map((item) => {
                const obj = {
                  label: item.mapName,
                  value: item.mapId,
                };
                this.floorArr.push(obj);
              });
            }
          }
        })
        .catch((err) => {});
    },
    giveDetail() {
      const objTarget = JSON.parse(this.objTarget);
      this.form = {
        mapId: objTarget.mapId,
        posId: objTarget.posId,
        // caseId: objTarget.caseId,
        type: objTarget.type,
        ctrlId: objTarget.ctrlId,
        assetId: objTarget.assetId,
      };
      this.rquestcaseArr("", objTarget);
      let assetNo = objTarget.assetNo;
      if (assetNo) {
        setTimeout(() => {
          this.$refs.tableCom.giveNoToSearch(assetNo);
        }, 100);
      }
    },
    rquestposId(val) {
      if (val) {
        this.rquestcaseArr("");
      } else {
        this.$set(this.form, "caseId", "");
      }
    },
    cancle() {
      this.handleClose(false);
    },
    sub() {
      // 触发表单校验
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 校验通过，执行提交逻辑
          let requestWay, msg, errmsg;
          const queryParams = {
            mapId: this.form.mapId,
            posId: this.form.posId,
            caseId: this.form.caseId,
            type: this.form.type,
            ctrlId: this.form.ctrlId,
            assetId: this.form.assetId,
          };
          if (this.id) {
            requestWay = editLocation;
            queryParams.alId = this.id;
            msg = "修改成功";
            errmsg = "修改失败";
          } else {
            requestWay = addLocation;
            msg = "新增成功";
            errmsg = "新增失败";
          }
          console.log("提交表单数据:", queryParams);
          requestWay(queryParams)
            .then((res) => {
              if (res.success) {
                this.$message.success(msg);
                this.handleClose(true);
              } else {
                this.$message.error(errmsg);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("表单校验未通过");
          return false;
        }
      });
    },
    handleClose(status) {
      this.form = {};
      // 重置表单
      this.$refs.form.resetFields();
      this.$refs.tableCom.resetQuery();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
